package o2sjsc.activity;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;

import o2sjsc.activity.util.SystemUiHider;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;

/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 * 
 * @see SystemUiHider
 */
public class DetailsActivity extends Activity implements OnClickListener {
	/**
	 * Whether or not the system UI should be auto-hidden after
	 * {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
	 */
	private static final boolean AUTO_HIDE = true;

	/**
	 * If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after
	 * user interaction before hiding the system UI.
	 */
	private static final int AUTO_HIDE_DELAY_MILLIS = 3000;

	/**
	 * If set, will toggle the system UI visibility upon interaction. Otherwise,
	 * will show the system UI visibility upon interaction.
	 */
	private static final boolean TOGGLE_ON_CLICK = true;

	/**
	 * The flags to pass to {@link SystemUiHider#getInstance}.
	 */
	private static final int HIDER_FLAGS = SystemUiHider.FLAG_HIDE_NAVIGATION;
	/**
	 * The instance of the {@link SystemUiHider} for this activity.
	 */
	
	private static String APP_ID = "411725048948170"; // Replace with your App ID

	// Instance of Facebook Class
	private AsyncFacebookRunner mAsyncRunner;
	private Facebook mfacebooks = new Facebook(APP_ID);
	String FILENAME = "AndroidSSO_data";
	private SharedPreferences mPrefs;
	
	private SystemUiHider mSystemUiHider;
	Button btnBack, btnShare;
	ImageView imgIncreaseSize;
	ImageView imgDecreaseSize;
	ImageView imgComment;
	ImageView imgRelated;
	TextView tvTitle,tvIntroduction/*, tvLableCreateDate, tvCreateDate*/;
	WebView wvContentDetail;
	int fontSize;
	LinearLayout lnfacebook,lntwitter,lnmail,lnmore;
	// Cached values.
	int mControlsHeight;
	int mShortAnimTime;
	View controlsView;
	View contentView;
	//static int countAccess =0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		hideStatusBar();
		setContentView(R.layout.activity_details);
		ActionBar actionBar = getActionBar();
		actionBar.setCustomView(R.layout.activity_content_detail_action_bar);
		actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
		btnBack = (Button) findViewById(R.id.btnBack);
		btnBack.setOnClickListener(this);
		btnShare = (Button) findViewById(R.id.btnShare);
		btnShare.setOnClickListener(this);

		tvTitle = (TextView) findViewById(R.id.tvTitle);
		tvIntroduction = (TextView) findViewById(R.id.tvIntroduction);
	/*	tvLableCreateDate = (TextView) findViewById(R.id.tvLBTime);
		tvCreateDate = (TextView) findViewById(R.id.tvTime);*/
		wvContentDetail = (WebView) findViewById(R.id.wvContentDetail);
		Bundle b = getIntent().getExtras();
		String contentId = b.getString("contentId");

/*		new ContentDetailAsynTask(this, contentId, tvTitle, tvLableCreateDate,
				tvCreateDate, wvContentDetail).execute();*/
		new ContentDetailAsynTask(this, contentId,tvTitle, wvContentDetail).execute();
		
		controlsView = findViewById(R.id.fullscreen_content_controls);
		contentView = findViewById(R.id.linear_content);
		
		// Set up an instance of SystemUiHider to control the system UI for
		// this activity.

		mSystemUiHider = SystemUiHider.getInstance(this, contentView,
				HIDER_FLAGS );
		mSystemUiHider.setup();
		mSystemUiHider
				.setOnVisibilityChangeListener(new SystemUiHider.OnVisibilityChangeListener() {
					// Cached values.
					int mControlsHeight;
					int mShortAnimTime;
					int countAccess=0;

					@Override
					@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
					public void onVisibilityChange(boolean visible) {
						
                      /*  if (DetailsActivity.countAccess % 2 == 0) {visible=true;}
                        else {visible=false;}
                        DetailsActivity.countAccess++;*/
						if(countAccess==0) {visible=true;}
						countAccess=1;
						if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
							// If the ViewPropertyAnimator API is available
							// (Honeycomb MR2 and later), use it to animate the
							// in-layout UI controls at the bottom of the
							// screen.
							if (mControlsHeight == 0) {
								mControlsHeight = controlsView.getHeight();
							}
							if (mShortAnimTime == 0) {
								mShortAnimTime = getResources().getInteger(
										android.R.integer.config_shortAnimTime);
							}
							controlsView
									.animate()
									.translationY(visible ? 0 : mControlsHeight)
									.setDuration(mShortAnimTime);
						} else {
							// If the ViewPropertyAnimator APIs aren't
							// available, simply show or hide the in-layout UI
							// controls.
							controlsView.setVisibility(visible ? View.VISIBLE
									: View.GONE);
						}

						if (visible && AUTO_HIDE) {
							// Schedule a hide().
							delayedHide(5000);
						}
					}
				});


		// Set up the user interaction to manually show or hide the system UI.

contentView.setOnClickListener(new OnClickListener() {
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if(TOGGLE_ON_CLICK){
			mSystemUiHider.toggle();
		}else{
			mSystemUiHider.show();
		}
	}
});
			

		imgIncreaseSize = (ImageView) findViewById(R.id.toolbar_zoomout);
		imgDecreaseSize = (ImageView) findViewById(R.id.toolbar_zoomin);
		imgComment = (ImageView) findViewById(R.id.toolbar_comment);
		imgRelated = (ImageView) findViewById(R.id.toolbar_related);

		imgIncreaseSize.setOnTouchListener(mDelayHideTouchListener);
		imgDecreaseSize.setOnTouchListener(mDelayHideTouchListener);
		imgComment.setOnTouchListener(mDelayHideTouchListener);
		imgRelated.setOnTouchListener(mDelayHideTouchListener);

		fontSize = wvContentDetail.getSettings().getDefaultFontSize();
		imgIncreaseSize.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				fontSizePlus();
			}
		});
		imgDecreaseSize.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				fontSizeMinus();
			}
		});
		imgComment.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Toast.makeText(DetailsActivity.this,
						"Chức năng hiện đang được phát triển",
						Toast.LENGTH_LONG).show();
			}
		});
		imgRelated.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Toast.makeText(DetailsActivity.this,
						"Chức năng hiện đang được phát triển",
						Toast.LENGTH_LONG).show();
			}
		});
	}
public void clickChangeStatusBar(){
	if(getActionBar().isShowing()){
		//getActionBar().hide();
		hideStatusBar();
	}else{
		//getActionBar().show();
		showStatusBar();
	}
}

	private void fontSizePlus() {
		fontSize++;
		this.changeFontSize(fontSize);
	}

	private void fontSizeMinus() {
		fontSize--;
		this.changeFontSize(fontSize);
	}

	private void changeFontSize(int value) {
		wvContentDetail.getSettings().setDefaultFontSize(fontSize);
	}
	private void hideStatusBar() {
        WindowManager.LayoutParams attrs = getWindow().getAttributes();
        attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
        getWindow().setAttributes(attrs);
    }

    private void showStatusBar() {
        WindowManager.LayoutParams attrs = getWindow().getAttributes();
        attrs.flags &= ~WindowManager.LayoutParams.FLAG_FULLSCREEN;
        getWindow().setAttributes(attrs);
    }

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);

		// Trigger the initial hide() shortly after the activity has been
		// created, to briefly hint to the user that UI controls
		// are available.
		// delayedShow(50);
		delayedHide(100);
	}

	/**
	 * Touch listener to use for in-layout UI controls to delay hiding the
	 * system UI. This is to prevent the jarring behavior of controls going away
	 * while interacting with activity UI.
	 */
	View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
		@Override
		public boolean onTouch(View view, MotionEvent motionEvent) {
			if (AUTO_HIDE) {
				delayedHide(AUTO_HIDE_DELAY_MILLIS);
			}
			return false;
		}
	};

	Handler mHideHandler = new Handler();
	Runnable mHideRunnable = new Runnable() {
		@Override
		public void run() {
			mSystemUiHider.hide();
		}
	};

	/**
	 * Schedules a call to hide() in [delay] milliseconds, canceling any
	 * previously scheduled calls.
	 */
	private void delayedHide(int delayMillis) {
		mHideHandler.removeCallbacks(mHideRunnable);
		mHideHandler.postDelayed(mHideRunnable, delayMillis);
	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		switch (arg0.getId()) {
		case R.id.btnBack:
			super.onBackPressed();
			break;
		case R.id.btnShare:
			// custom dialog
			final Dialog dialog = new Dialog(this);
			dialog.getWindow();
			dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
			dialog.setContentView(R.layout.share_list);
			dialog.show();

			// Action onClick Linear Layout FaceBook

			lnfacebook = (LinearLayout) dialog.findViewById(R.id.linearface);
			lnfacebook.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if (! mfacebooks.isSessionValid()) {
						loginToFacebook();
						postToWall();
					}
					else {
						postToWall();
					}
					
					loginToFacebook();
					dialog.hide();
				}
			});

			// Action onClick Linear Layout Twitter

			lntwitter = (LinearLayout) dialog.findViewById(R.id.lineartw);
			lntwitter.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Toast.makeText(DetailsActivity.this,
							"Chức năng Share Twitter đang được phát triển",
							Toast.LENGTH_SHORT).show();
					dialog.hide();
				}
			});

			// Action onClick Linear Layout Gmail

			lnmail = (LinearLayout) dialog.findViewById(R.id.linearmail);
			lnmail.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Toast.makeText(DetailsActivity.this,
							"Chức năng Share Gmail đang được phát triển",
							Toast.LENGTH_SHORT).show();
					dialog.hide();
				}
			});

			// Action onClick Linear Layout Share more

			lnmore = (LinearLayout) dialog.findViewById(R.id.linearmore);
			lnmore.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Intent intent = new Intent(Intent.ACTION_SEND);
					intent.setType("text/plain");
					intent.putExtra(Intent.EXTRA_TEXT, "" + tvTitle.getText()
							+ " http://techs.vn " + Global.Link);
					intent.putExtra(android.content.Intent.EXTRA_SUBJECT,
							"Check out this site!");
					startActivity(Intent.createChooser(intent, "Share"));

					dialog.hide();
				}
			});

			break;
		default:
			break;
		}
	}
	
	//Xử lý login facebook
	
		public void loginToFacebook() {

			mPrefs = getPreferences(MODE_PRIVATE);
			String access_token = mPrefs.getString("access_token", null);
			long expires = mPrefs.getLong("access_expires", 0);

			if (access_token != null) {
				mfacebooks.setAccessToken(access_token);
				Log.d("FB Sessions", "" + mfacebooks.isSessionValid());
			}

			if (expires != 0) {
				mfacebooks.setAccessExpires(expires);
			}

			if (!mfacebooks.isSessionValid()) {
				mfacebooks.authorize(this,
				new String[] { "email", "publish_stream" },
				new DialogListener() {

					@Override
					public void onCancel() {
						// Function to handle cancel event
					}

					@Override
					public void onComplete(Bundle values) {
						// Function to handle complete event
						// Edit Preferences and update facebook acess_token
						SharedPreferences.Editor editor = mPrefs.edit();
						editor.putString("access_token",
								mfacebooks.getAccessToken());
						editor.putLong("access_expires",
								mfacebooks.getAccessExpires());
						editor.commit();

						// Making Login button invisible
						
					}

					@Override
					public void onError(DialogError error) {
						// Function to handle error

					}

					@Override
					public void onFacebookError(FacebookError fberror) {
						// Function to handle Facebook errors

					}

				});
			}
		}
		
		@Override
		public void onActivityResult(int requestCode, int resultCode, Intent data) {
			super.onActivityResult(requestCode, resultCode, data);
			mfacebooks.authorizeCallback(requestCode, resultCode, data);
		}
		
		
		
		//post wall
		public void postToWall() {
			String link="http://techs.vn/"+Global.Link;
			String thum_img="http://cdn1.webbiresources.com/portals/"+Global.Thumb_Img;
			Bundle params= new Bundle();
			params.putString("name", tvTitle.getText().toString());
			params.putString("link", link);
			params.putString("picture", thum_img);
			
			// post on user's wall.
			mfacebooks.dialog(this, "feed",params, new DialogListener() {

				@Override
				public void onFacebookError(FacebookError e) {
				}

				@Override
				public void onError(DialogError e) {
				}

				@Override
				public void onComplete(Bundle values) {
				}

				@Override
				public void onCancel() {
				}
			});

		}
	//logout facebook
		public void logoutFromFacebook() {
			mAsyncRunner.logout(this, new RequestListener() {
				@Override
				public void onComplete(String response, Object state) {
					Log.d("Logout from Facebook", response);
					if (Boolean.parseBoolean(response) == true) {
						runOnUiThread(new Runnable() {

							@Override
							public void run() {
								
							}

						});

					}
				}

				@Override
				public void onIOException(IOException e, Object state) {
				}

				@Override
				public void onFileNotFoundException(FileNotFoundException e,
						Object state) {
				}

				@Override
				public void onMalformedURLException(MalformedURLException e,
						Object state) {
				}

				@Override
				public void onFacebookError(FacebookError e, Object state) {
				}
			});
		}
}
